package com.jilintongyi.jlcrtvu.annotation;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jilintongyi.jlcrtvu.entity.SysLog;
import com.jilintongyi.jlcrtvu.entity.SysUser;
import com.jilintongyi.jlcrtvu.service.LogService;
import com.jilintongyi.jlcrtvu.service.UserService;
import com.jilintongyi.jlcrtvu.util.HttpUtils;
import com.jilintongyi.jlcrtvu.util.UserUtils;

import io.swagger.annotations.ApiOperation;

/**
 * 日志切面
 */
@Aspect
@Component
public class LogAspect {
	@Autowired
	UserService userService;

	@Autowired
	LogService logService;

	@Pointcut("@annotation(Log)") // 切入点
	private void logPointCut() {

	}

	@Before("logPointCut()") // 切入点前执行
	public void saveLog(JoinPoint joinPoint) throws JsonProcessingException {
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();
		SysLog SysLog = new SysLog();
		Log log = method.getAnnotation(Log.class);
		ApiOperation apiOperation = method.getAnnotation(ApiOperation.class); // Swagger 接口描述
		if (null != SysLog) {
			String className = joinPoint.getTarget().getClass().getName();
			String methodName = signature.getName();
			String content = "";
			Object[] args = joinPoint.getArgs();
			Object params = "";
			for (int i = 0; i < args.length; i++) {
				// 方法名==login 并且遍历到密码 则结束循环
				if (methodName.equals("login") && i == 1) {
					break;
				}
				Object o = args[i];
				if (o instanceof MultipartFile) {
					params += "," + ((MultipartFile) o).getOriginalFilename();
				} else {
					ObjectMapper objectMapper = new ObjectMapper();
					params += "," + objectMapper.writeValueAsString(o);
				}
			}
			if (StringUtils.hasText(log.content())) {
				content = log.content();
			} else if (null != apiOperation) {
				content = apiOperation.value();
			}
			SysLog.setContent(content + " " + className + "." + methodName + "()" + params);
		}
		SysLog.setIp(HttpUtils.getIpAddress());
		if (!UserUtils.getCurrentUsername().equals("anonymousUser")) {
			SysUser user = userService.findByUsername(UserUtils.getCurrentUsername());
			if (null != user) {
				SysLog.setUser(user);
			}
		}
		logService.save(SysLog);
	}

}
